﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using I2CDll;

namespace DebugTools
{
    public partial class Form_Main : Form
    {
        public static Ininfo ininfo;
        public Ins ins;
        public AC_Source AC;
        public DC_Source DC;
        public int nFlag = 1;
        public string Log;
        Color _Color_Fault = Color.OrangeRed;
        Color _Color_Warn = Color.OrangeRed;
        Color _Color_None = Color.DarkSeaGreen;
        I2C i2cTool;

        protected string[] ACs = new string[10];
        protected string[] DCs = new string[10];

        public Form_Main()
        {
            InitializeComponent();

            ins = new Ins();
            ACs[0] = "GPIB0::30::INSTR";
            DCs[0] = "GPIB0::29::INSTR";
            Log = string.Empty;
        }

        private void btn_Ins_Click(object sender, EventArgs e)
        {
            ins.ShowDialog();
            if (!ins.Source_ID.Equals(""))
            {
                if (checkBoxAC.Checked)
                {
                    if (isInArray(DCs, ins.Source_ID))
                    {
                        MessageBox.Show("AC Source ID: " + ins.Source_ID + " is error!\n请重新选择。");
                        return;
                    }
                    AC = new AC_Source(ins.Source_ID);
                }
                else
                {
                    if (isInArray(ACs, ins.Source_ID))
                    {
                        MessageBox.Show("DC Source ID: " + ins.Source_ID + " is error!\n请重新选择。");
                        return;
                    }
                    DC = new DC_Source(ins.Source_ID);
                }
                //timer1.Enabled = true;
            }
        }

        private void btn_Set_Click(object sender, EventArgs e)
        {
            float fVolt = 0,
                fValue = 0;

            try
            {
                fVolt = float.Parse(textBox_Volt.Text);
            }
            catch (Exception)
            {
                MessageBox.Show("请检查电压输入框！", "Error");
            }
            try
            {
                fValue = float.Parse(textBox_Curr.Text);
            }
            catch (Exception)
            {
                MessageBox.Show("请检查电流输入框！", "Error");
            }

            if (ins.Source_ID != null)
            {
                if (checkBoxAC.Checked)
                {
                    if (null != AC)
                    {
                        if (AC.m_mbSession != null)
                            AC.Set_VF(fVolt, fValue);
                    }
                    return;
                }
                else
                {
                    if (null != DC)
                    {
                        if (DC.m_mbSession != null)
                            DC.Set_VC(fVolt, fValue);
                    }
                    return;
                }
            }
            else
                MessageBox.Show("请先选择Source!", "Error");
        }

        private void btn_OFF_Click(object sender, EventArgs e)
        {
            //if (ins.Source_ID != null)
            //{
            //    if (checkBoxAC.Checked)
            //    {
            //        if (null != AC)
            //        {
            //            if (AC.m_mbSession != null)
            //                AC.ONorOFF(false);
            //        }
            //    }
            //    else
            //    {
            //        if (null != DC)
            //        {
            //            if (DC.m_mbSession != null)
            //                DC.ONorOFF(false);
            //        }
            //    }
            //}
            //else
            //    MessageBox.Show("请先选择Source!", "Error");

            //PM_ZLG310 pm = new PM_ZLG310("GPIB0::1::INSTR");
            PowerMeter pm = new PowerMeter("GPIB0::9::INSTR");
            pm = new PM_Chroma("GPIB0::9::INSTR");
            pm.Init();
            tbxLog.Text = pm.Meas_Volt().ToString();
        }

        private void checkBoxAC_CheckedChanged(object sender, EventArgs e)
        {
            label2.Text = checkBoxAC.Checked ? "频率: " : "电流: ";
            textBox_Volt.Text = checkBoxAC.Checked ? "230" : "270";
            textBox_Curr.Text = checkBoxAC.Checked ? "50" : "20";
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            string path = System.IO.Path.Combine(Application.StartupPath, "General.ini");
            ininfo = new Ininfo(path);

            if (ininfo._sTypeI2CIO == "MCP")
                mCPToolStripMenuItem.Checked = true;
            else if (ininfo._sTypeI2CIO == "NI8451")
                nI8451ToolStripMenuItem.Checked = true;

            //EricStatus = new EricsonStatus();
            Init_dgv_Status();
        }

        private void Form_Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            ininfo.Save();
            SaveLog();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Interval = Convert.ToInt32(tbxInterval.Text);
            timer2.Interval = Convert.ToInt32(tbxInterval2.Text);
            float fVolt = 0,
                fValue = 0;

            try
            {
                fVolt = float.Parse(textBox_Volt.Text);
            }
            catch (Exception)
            {
                timer1.Enabled = false;
                timer2.Enabled = false;
                MessageBox.Show("请检查电压输入框！", "Error");
            }
            try
            {
                fValue = float.Parse(textBox_Curr.Text);
            }
            catch (Exception)
            {
                timer1.Enabled = false;
                timer2.Enabled = false;
                MessageBox.Show("请检查电流输入框！", "Error");
            }

            if (nFlag < 0)
            {
                if (ins.Source_ID != null)
                {
                    if (checkBoxAC.Checked)
                    {
                        if (null != AC)
                        {
                            if (AC.m_mbSession != null)
                                AC.Set_VF(fVolt, fValue);
                        }
                    }
                    else
                    {
                        if (null != DC)
                        {
                            if (DC.m_mbSession != null)
                                DC.Set_VC(fVolt, fValue);
                        }
                    }
                }
                else
                {
                    timer1.Enabled = false;
                    timer2.Enabled = false;
                    MessageBox.Show("请先选择Source!", "Error");
                }
            }
            else
            {
                if (ins.Source_ID != null)
                {
                    if (checkBoxAC.Checked)
                    {
                        if (null != AC)
                        {
                            if (AC.m_mbSession != null)
                                AC.ONorOFF(false);
                        }
                    }
                    else
                    {
                        if (null != DC)
                        {
                            if (DC.m_mbSession != null)
                                DC.ONorOFF(false);
                        }
                    }
                }
                else
                {
                    timer1.Enabled = false;
                    timer2.Enabled = false;
                    MessageBox.Show("请先选择Source!", "Error");
                }
            }

            nFlag *= -1;
            //if (checkBoxAC.Checked)
            //{
            //    if (null != AC)
            //        if (AC.m_mbSession != null)
            //        {
            //            lbl_V.Text = AC.Meas_Volt().ToString();
            //            lbl_C.Text = AC.Meas_Curr().ToString();
            //        }
            //    return;
            //}
            //else
            //{

            //    if (null != DC)
            //    {
            //        if (DC.m_mbSession != null)
            //        {
            //            lbl_V.Text = DC.Meas_Volt().ToString();
            //            lbl_C.Text = DC.Meas_Curr().ToString();
            //        }
            //    }
            //    return;
            //}
        }

        bool isInArray(string[] Array, string element)
        {
            foreach (string str in Array)
                if (str == element)
                    return true;
            return false;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            i2cTool = new I2C(ininfo._sTypeI2CIO);
            timer1.Interval = Convert.ToInt32(tbxInterval.Text);
            timer2.Interval = Convert.ToInt32(tbxInterval2.Text);
            timer1.Enabled = true;
            timer2.Enabled = true;
        }

        private void btnEnd_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            timer2.Enabled = false;
        }

        private void addressSettingToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form_AddressSet form = new Form_AddressSet();
            form.ShowDialog();
        }

        private void mCPToolStripMenuItem_Click(object sender, EventArgs e)
        {
            I2CTypeChecked(sender);
            ininfo._sTypeI2CIO = "MCP";
        }

        private void nI8451ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            I2CTypeChecked(sender);
            ininfo._sTypeI2CIO = "NI8451";
        }

        private void I2CTypeChecked(object sender)
        {
            mCPToolStripMenuItem.Checked = false;
            nI8451ToolStripMenuItem.Checked = false;
            ((ToolStripMenuItem)sender).Checked = true;
        }

        private string GetI2CResult()
        {
            bool bRet = true;
            byte u8Addr = Convert.ToByte(int.Parse(ininfo._sAddressPSU, System.Globalization.NumberStyles.HexNumber));
            byte[] r_data = new byte[256];
            string log = "Time: " + DateTime.Now.ToString("G") + "\r\n";
            //79h，7Ah，7Bh，7Ch，7Dh，81h
            if (i2cTool != null)
            {
                i2cTool.PMBus_Read_Word(u8Addr, 0x79, r_data);
                log += "79H: " + Convert.ToString(r_data[1], 16) + Convert.ToString(r_data[0], 16) + ";\r\n";
                bRet = (r_data[0] & 0x08) == 0x08 ? true : false;
                if (!bRet)
                {
                    timer1.Enabled = false;
                    timer2.Enabled = false;
                    log += "=====================False=====================\r\n";
                }
                r_data[0] = 0;
                r_data[1] = 0;
                i2cTool.PMBus_Read_Byte(u8Addr, 0x7A, r_data);
                log += "7AH: " + Convert.ToString(r_data[0], 16) + ";\r\n";
                r_data[0] = 0;
                r_data[1] = 0;
                i2cTool.PMBus_Read_Byte(u8Addr, 0x7B, r_data);
                log += "7BH: " + Convert.ToString(r_data[0], 16) + ";\r\n";
                r_data[0] = 0;
                r_data[1] = 0;
                i2cTool.PMBus_Read_Byte(u8Addr, 0x7C, r_data);
                log += "7CH: " + Convert.ToString(r_data[0], 16) + ";\r\n";
                r_data[0] = 0;
                r_data[1] = 0;
                i2cTool.PMBus_Read_Byte(u8Addr, 0x7D, r_data);
                log += "7DH: " + Convert.ToString(r_data[0], 16) + ";\r\n";
                r_data[0] = 0;
                r_data[1] = 0;
                i2cTool.PMBus_Read_Byte(u8Addr, 0x81, r_data);
                log += "81H: " + Convert.ToString(r_data[0], 16) + ";\r\n\r\n";
                r_data[0] = 0;
                r_data[1] = 0;
            }
            return log;
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            if (nFlag < 0)
                tbxLog.Text += GetI2CResult();

            if (checkBoxAC.Checked)
            {
                if (null != AC)
                    if (AC.m_mbSession != null)
                    {
                        lbl_V.Text = AC.Meas_Volt().ToString();
                        lbl_C.Text = AC.Meas_Curr().ToString();
                    }
                return;
            }
            else
            {

                if (null != DC)
                {
                    if (DC.m_mbSession != null)
                    {
                        lbl_V.Text = DC.Meas_Volt().ToString();
                        lbl_C.Text = DC.Meas_Curr().ToString();
                    }
                }
                return;
            }
        }

        private void tbxLog_TextChanged(object sender, EventArgs e)
        {
            tbxLog.SelectionStart = tbxLog.Text.Length;
            tbxLog.ScrollToCaret();
        }

        private void SaveLog()
        {
            string Path = System.IO.Path.Combine(Application.StartupPath, "Log");
            DirectoryInfo dirInfo = new DirectoryInfo(Path);
            if (!dirInfo.Exists)
                dirInfo.Create();
            if (tbxLog.Text != "")
            {
                Path = System.IO.Path.Combine(Path, DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + ".txt");
                StreamWriter sw = new StreamWriter(Path, false, System.Text.Encoding.Default);
                try
                {
                    sw.Write(tbxLog.Text);
                    sw.Close();
                }
                catch (Exception)
                {
                    throw (new ApplicationException("无法创建文件"));
                }
            }
        }

        private void Init_dgv_Status()
        {
            dgv_79.RowCount = 16;
            dgv_7A.RowCount = 8;
            dgv_7B.RowCount = 8;
            dgv_7C.RowCount = 8;
            dgv_7D.RowCount = 8;
            dgv_81.RowCount = 8;

            for (int i = 0; i < 16; i++)
            {
                dgv_79.Rows[i].Cells[0].Value = (i + 1).ToString();
                //dgv_79.Rows[i].Cells[1].Value = EricStatus.EricStatus1.State1_List[i];
            }

            for (int i = 0; i < 8; i++)
            {
                dgv_7A.Rows[i].Cells[0].Value = (i + 1).ToString();
                dgv_7A.Rows[i].Cells[1].Value = "ce";

                dgv_7B.Rows[i].Cells[0].Value = (i + 1).ToString();
                dgv_7B.Rows[i].Cells[1].Value = "ds";

                dgv_7C.Rows[i].Cells[0].Value = (i + 1).ToString();
                dgv_7C.Rows[i].Cells[1].Value = "be";

                dgv_7D.Rows[i].Cells[0].Value = (i + 1).ToString();
                //dgv_7D.Rows[i].Cells[1].Value = EricStatus.EricStatus1.State1_List[i];

                dgv_81.Rows[i].Cells[0].Value = (i + 1).ToString();
                dgv_81.Rows[i].Cells[1].Value = "sgdsf";

            }

        }

        private void Set_Status_7A()
        {

            //dgv_7A.Rows[0].Cells[1].Style.BackColor = EricStatus.EricStatus2.b12VOcp == true ? _Color_Fault : _Color_None;
            //dgv_7A.Rows[1].Cells[1].Style.BackColor = EricStatus.EricStatus2.b12VScp == true ? _Color_Fault : _Color_None;

            //dgv_AA.Rows[2].Cells[1].Style.BackColor =
            //     EricStatus.EricStatus2.bIoutOcp == true ? _Color_Warn : _Color_None;
            //dgv_AA.Rows[3].Cells[1].Style.BackColor =
            //     EricStatus.EricStatus2.b12VPro == true ? _Color_Fault : _Color_None;
            //dgv_AA.Rows[4].Cells[1].Style.BackColor =
            //     EricStatus.EricStatus2.b48VScp == true ? _Color_Warn : _Color_None;
            //dgv_AA.Rows[5].Cells[1].Style.BackColor =
            //     EricStatus.EricStatus2.b12VScp == true ? _Color_Fault : _Color_None;
            //dgv_AA.Rows[6].Cells[1].Style.BackColor =
            //    EricStatus.EricStatus2.bVinUVP == true ? _Color_Warn : _Color_None;
            //dgv_AA.Rows[7].Cells[1].Style.BackColor =
            //   EricStatus.EricStatus2.b12VOcp == true ? _Color_Fault : _Color_None;
        }
    }
}
